package com.platform.api;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.google.common.collect.Maps;
import com.platform.annotation.IgnoreAuth;
import com.platform.annotation.LoginUser;
import com.platform.annotation.RedisCache;
import com.platform.cache.J2CacheUtils;
import com.platform.dao.ApiOrderMapper;
import com.platform.entity.*;
import com.platform.service.ApiOrderService;
import com.platform.service.ApiUserService;
import com.platform.service.SysConfigService;
import com.platform.util.ApiBaseAction;
import com.platform.utils.CharUtil;
import com.platform.utils.Constant;
import com.platform.utils.SmsUtil;
import com.platform.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 作者: @author Harmon <br>
 * 时间: 2017-08-11 08:32<br>
 * 描述: ApiIndexController <br>
 */
@Api(tags = "会员验证")
@RestController
@RequestMapping("/api/user")
public class ApiUserController extends ApiBaseAction {
    @Autowired
    private ApiUserService userService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private ApiOrderService apiOrderService;

    /**
     * 新建用户
     * @param loginUser
     * @return
     */
    @IgnoreAuth
    @PostMapping("createNewUser")
    public Object createNewUser(@RequestBody UserVo loginUser){
    	String referrer = loginUser.getReferrer();
    	String authCode = loginUser.getAuthCode();
    	String mobile = loginUser.getMobile();
    	if(org.apache.commons.lang.StringUtils.isBlank(authCode)){
			return toResponsFail("验证码错误");
		}

        if(org.apache.commons.lang.StringUtils.isNotBlank(referrer)){
            UserVo referrerUser = userService.queryByMobile(referrer);
            if(referrerUser == null){
                return toResponsFail("推荐人不存在");
            }
			loginUser.setGroupId(referrerUser.getGroupId());
        }

        UserVo existUser = userService.queryByMobile(loginUser.getMobile());
        if(existUser != null){
            return toResponsFail("该手机号码已存在");
        }

		String existCode = J2CacheUtils.get(mobile).toString();
        if(!org.apache.commons.lang.StringUtils.equals(authCode, existCode)){
			return toResponsFail("验证码错误");
		}
        userService.save(loginUser);
        return loginUser;
    }

    /**
     * 发送短信
     * @return
     */
    @IgnoreAuth
    @GetMapping("sendSms")
    public Object sendSms(String mobile){
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4Fgxuxt6B43Wd2Pxf7Gg", "p3sgrTntkNM6c8uDW7tg1hGEiClE2B");
        IAcsClient client = new DefaultAcsClient(profile);
        String code = CharUtil.getRandomNum(6);
        JSONObject param = new JSONObject();
        param.put("code", code);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", "LZCP");
        request.putQueryParameter("TemplateCode", "SMS_174991807");
        request.putQueryParameter("TemplateParam", param.toJSONString());
        CommonResponse response = new CommonResponse();
        try {
            response = client.getCommonResponse(request);
            J2CacheUtils.put(mobile, code);
            System.out.println(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }

        return response.getData();
    }

    @ApiOperation(value = "添加代理商")
    @PostMapping("addMyMember")
    public Object addMyMember(@LoginUser UserVo loginUser, @RequestBody UserVo newUser){
        newUser.setReferrer(loginUser.getMobile());
        UserVo existUser = userService.queryByMobile(newUser.getMobile());
        if(existUser != null){
            return toResponsFail("该手机号码已存在");
        }
        userService.save(newUser);
        return newUser;
    }

    @ApiOperation(value = "我的代理商成员")
    @PostMapping("myGroup")
    public Object myGroup(@LoginUser UserVo loginUser){
        List<UserVo> myGroupUserList = userService.queryByGroupId(loginUser.getGroupId());
        return myGroupUserList;
    }

    @ApiOperation(value = "我的积分明细列表")
    @PostMapping("myScoreList")
    public Object myScoreList(@LoginUser UserVo loginUser){
        List<UserVo> myGroupUserList = userService.queryByGroupId(loginUser.getGroupId());
        return myGroupUserList;
    }

	@ApiOperation(value = "我的个人主页")
	@PostMapping("myPage")
	public Object myPage(@LoginUser UserVo loginUser){
        MyInfoVo myInfoVo = new MyInfoVo();
        BigDecimal mySales = new BigDecimal("0");
        BigDecimal groupSales = new BigDecimal("0");
        Map<String, Object> params = Maps.newHashMap();
        params.put("user_id", loginUser.getId());
        List<OrderVo> orderList = apiOrderService.queryList(params);
        for(OrderVo orderVo : orderList){
            BigDecimal orderPrice = orderVo.getOrder_price();
            mySales = mySales.add(orderPrice);
        }
        myInfoVo.setMySales(mySales);

		List<UserVo> myGroupUserList = userService.queryByGroupId(loginUser.getGroupId());
		for(UserVo userVo : myGroupUserList){
            List<OrderVo> groupOrderList = apiOrderService.queryList(params);
            for(OrderVo orderVo : groupOrderList){
                BigDecimal orderPrice = orderVo.getOrder_price();
                groupSales = groupSales.add(orderPrice);
            }
        }
        myInfoVo.setGroupSales(groupSales);

		myInfoVo.setRule(sysConfigService.getValue("jiangliguize", ""));
        myInfoVo.setNickName(loginUser.getNickname());
        myInfoVo.setAvatar(loginUser.getAvatar());
        myInfoVo.setLevel(loginUser.getUser_level_id());
		return myInfoVo;
	}

    /**
     * 发送短信
     */
    @ApiOperation(value = "发送短信")
    @PostMapping("smscode")
    public Object smscode(@LoginUser UserVo loginUser) {
        JSONObject jsonParams = getJsonRequest();
        String phone = jsonParams.getString("phone");
        // 一分钟之内不能重复发送短信
        SmsLogVo smsLogVo = userService.querySmsCodeByUserId(loginUser.getUserId());
        if (null != smsLogVo && (System.currentTimeMillis() / 1000 - smsLogVo.getLog_date()) < 1 * 60) {
            return toResponsFail("短信已发送");
        }
        //生成验证码
        String sms_code = CharUtil.getRandomNum(4);
        String msgContent = "您的验证码是：" + sms_code + "，请在页面中提交验证码完成验证。";
        // 发送短信
        String result = "";
        //获取云存储配置信息
        SmsConfig config = sysConfigService.getConfigObject(Constant.SMS_CONFIG_KEY, SmsConfig.class);
        if (StringUtils.isNullOrEmpty(config)) {
            return toResponsFail("请先配置短信平台信息");
        }
        if (StringUtils.isNullOrEmpty(config.getName())) {
            return toResponsFail("请先配置短信平台用户名");
        }
        if (StringUtils.isNullOrEmpty(config.getPwd())) {
            return toResponsFail("请先配置短信平台密钥");
        }
        if (StringUtils.isNullOrEmpty(config.getSign())) {
            return toResponsFail("请先配置短信平台签名");
        }
        try {
            /**
             * 状态,发送编号,无效号码数,成功提交数,黑名单数和消息，无论发送的号码是多少，一个发送请求只返回一个sendid，如果响应的状态不是“0”，则只有状态和消息
             */
            result = SmsUtil.crSendSms(config.getName(), config.getPwd(), phone, msgContent, config.getSign(), "", "");
        } catch (Exception e) {

        }
        String arr[] = result.split(",");

        if ("0".equals(arr[0])) {
            smsLogVo = new SmsLogVo();
            smsLogVo.setLog_date(System.currentTimeMillis() / 1000);
            smsLogVo.setUser_id(loginUser.getUserId());
            smsLogVo.setPhone(phone);
            smsLogVo.setSms_code(sms_code);
            smsLogVo.setSms_text(msgContent);
            userService.saveSmsCodeLog(smsLogVo);
            return toResponsSuccess("短信发送成功");
        } else {
            return toResponsFail("短信发送失败");
        }
    }

    /**
     * 获取当前会员等级
     *
     * @param loginUser
     * @return
     */
    @ApiOperation(value = "获取当前会员等级")
    @PostMapping("getUserLevel")
    public Object getUserLevel(@LoginUser UserVo loginUser) {
        String userLevel = userService.getUserLevel(loginUser);
        return toResponsSuccess(userLevel);
    }

    /**
     * 绑定手机
     */
    @ApiOperation(value = "绑定手机")
    @PostMapping("bindMobile")
    public Object bindMobile(@LoginUser UserVo loginUser) {
        JSONObject jsonParams = getJsonRequest();
        SmsLogVo smsLogVo = userService.querySmsCodeByUserId(loginUser.getUserId());

        String mobile_code = jsonParams.getString("mobile_code");
        String mobile = jsonParams.getString("mobile");

        if (!mobile_code.equals(smsLogVo.getSms_code())) {
            return toResponsFail("验证码错误");
        }
        UserVo userVo = userService.queryObject(loginUser.getUserId());
        userVo.setMobile(mobile);
        userService.update(userVo);
        return toResponsSuccess("手机绑定成功");
    }
}